package com.example.design.shejimoshi.action.responsibility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 处理器链
 */
@Component
public class HandlerChain {
    // @Autowired可以注入List并且还可以用Order来指定添加顺序
    @Autowired
    private List<AbstractHandler> abstractHandleList;

    private AbstractHandler abstractHandler;

    //spring注入后自动执行，责任链的对象连接起来
    @PostConstruct
    public void initializeChainFilter() {
        for (int i = 0; i < abstractHandleList.size(); i++) {
            if (i == 0) {
                // 将链子的第一个元素赋给abstractHandler，方便执行
                abstractHandler = abstractHandleList.get(0);
            } else {
                // 构造链子，因为list本来就是有顺序的，直接遍历往下接链子即可
                AbstractHandler currentHander = abstractHandleList.get(i - 1);
                AbstractHandler nextHander = abstractHandleList.get(i);
                currentHander.setNextHandler(nextHander);
            }
        }
    }

    //直接调用这个方法使用
    public void exec(UserDO userDO) {
        abstractHandler.filter(userDO);
        return ;
    }
}